package com.sz.test.controller;


import com.sz.test.annotation.Role;
import com.sz.test.common.R;
import com.sz.test.context.SecurityContext;
import com.sz.test.pojo.User;
import com.sz.test.util.MD5;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

@RestController
public class UserController {

    @Role(value = Role.GUEST)
    @PostMapping(value = "/api/login.action")
    public R login(String username, String password) {
        if (username.equals("admin") && password.equals("123456")) {
            String token = MD5.encrypt("admin123456");
            User user = new User(1, "admin", null, 2);
            SecurityContext.getTokenMap().put(token, user);
            return R.ok("登录成功").data("token", token);
        } else if (username.equals("user") && password.equals("123456")) {
            String token = MD5.encrypt("user123456");
            User user = new User(2, "user", null, 1);
            SecurityContext.getTokenMap().put(token, user);
            return R.ok("登录成功").data("token", token);
        }
        return R.error("登录失败：密码错误");
    }

    @Role(value = Role.USER)
    @GetMapping("/api/user.action")
    public R getUser(@RequestParam String id) {
        return R.ok("用户请求成功");
    }

    @Role(value = Role.ADMIN)
    @DeleteMapping("/api/user.action")
    public R deleteUser(@RequestParam String id) {
        return R.ok("管理员请求成功");
    }
}
